<?php


namespace chixian\Libraries\Exception\Handler;


use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use chixian\Libraries\HttpServer\ResponseInterface as ResponseInterfaceLib;

class HttpExceptionHandler extends \Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler
{
    /** @var ResponseInterfaceLib */
    protected $response;

    /**
     * HttpExceptionHandler constructor.
     * @param StdoutLoggerInterface $logger
     * @param FormatterInterface $formatter
     * @param ResponseInterfaceLib $response
     */
    public function __construct(StdoutLoggerInterface $logger, FormatterInterface $formatter, ResponseInterfaceLib $response)
    {
        parent::__construct($logger, $formatter);
        $this->response = $response;
    }

    /**
     * @param Throwable $throwable
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $message = sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile());
        $this->logger->error($message, ['trace' => $throwable->getTraceAsString()]);
        $this->stopPropagation();
        return $this->response->withStatus($throwable->getStatusCode())->rJson([], $throwable->getStatusCode(), new SwooleStream($throwable->getMessage()));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof HttpException;
    }
}